﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IotWeek2Day9.EFCore;
using static System.Math; //直接引用静态类的方法
using IotWeek2Day9.Models;
using Microsoft.EntityFrameworkCore;
using IotWeek2Day9.WebApi.Models;

using System.IO; //文件操作
using Microsoft.AspNetCore.Hosting; //ASPNET Core的托管环境
using Microsoft.Extensions.Caching.Distributed;

namespace IotWeek2Day9.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ItemController : ControllerBase
    {
        /// <summary>
        /// 私有字段，用来操作数据库（泛型仓储接口）
        /// </summary>
        private readonly IRepository<Item> _itemRepository;
        private readonly DBHelper _helper;
        private readonly IDistributedCache _cache;


        ////构造函数进行依赖注入
        public ItemController(IRepository<Item> itemRepository, DBHelper helper, IDistributedCache cache)
        {
            this._itemRepository = itemRepository; //依赖注入
            _helper = helper;
            _cache = cache;
        }

        /// <summary>
        /// 显示所有的待办事项
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetList(int pageIndex=1, int pageSize=10, string itemTitle=null, int empId=0)
        {
            //定义一个可查询对象（SQL语句）
            //IQueryable<ItemDto> query = from a in _itemRepository.GetAll().Include("Emp")
            //                         where string.IsNullOrEmpty(itemTitle) || a.Title.Contains(itemTitle)
            //                         select new ItemDto { 
            //                            Contact = a.Contact,
            //                            Title = a.Title,
            //                            EmpName = a.Emp.EName,
            //                            EndTime = a.EndTime,
            //                            StartTime = a.StartTime,
            //                            ItemId = a.ItemId,
            //                            Status = Enum.GetName(typeof(ItemStatus), a.Status)
            //                         };

            var query = _itemRepository.GetAll().Include("Emp");
            if (!string.IsNullOrEmpty(itemTitle)) //模糊查询
            {
                query = query.Where(x => x.Title.Contains(itemTitle));
            }
            if(empId != 0) //下拉查询
            {
                query = query.Where(x => x.EmpId == empId);
            }

            //1.总条数
            int totalCount = query.Count();

            //2.总页数
            int pageCount = Convert.ToInt32(Ceiling(totalCount * 1.0 / pageSize));

            //3.结果数据集
            List<ItemDto> data = query.OrderByDescending(x => x.StartTime)
                                     .Skip((pageIndex - 1) * pageSize)
                                     .Take(pageSize)
                                     .Select( a=>new ItemDto {
                                         Contact = a.Contact,
                                         Title = a.Title,
                                         EmpName = a.Emp.EName,
                                         EndTime = a.EndTime,
                                         StartTime = a.StartTime,
                                         ItemId = a.ItemId,
                                         Status = a.Status,
                                         StatusString = a.Status.ToString(),
                                         FilePath = a.FilePath      //返回图片的相对路径
                                     })
                                     .ToList();  //ToList只在最后执行一次

            return Ok(new { totalCount, pageCount, data });
        }


        [HttpPost]
        public IActionResult Create(CreateItemDto input)
        {
            
            if (ModelState.IsValid) //后台的模型验证（验证有效）
            {
                Random r = new Random();

                //实例化实体模型对象
                Item item = new Item
                {
                    //Status = ItemStatus.待办,      //不是用户输入的，是默认状态
                    Contact = input.Contact,
                    EmpId = input.EmpId,
                    EndTime = input.EndTime,
                    ItemDetail = input.ItemDetail,
                    ItemNo = "S" + r.Next(1, 1000),//不是用户输入的，流水号要后台生成
                    StartTime = input.StartTime,
                    Title = input.Title,
                };

                int result = _itemRepository.Add(item);

                return Ok(new { msg = result > 0 ? "创建成功" : "创建失败", result });
            }

            //如果验证无效
            return Ok(new { msg = "数据错误", result = -1 });
            

        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete(string ids)
        {
            //进行删除
            foreach (var i in ids.Split(','))
            {
                int id = int.Parse(i);
                _itemRepository.Delete(id);
            }

            return Ok(new { msg = "删除成功", result= 1});
        }

        //[HttpPost]
        //public IActionResult UploadFile(IFormFile file, [FromServices] IWebHostEnvironment environment)
        //{
        //    //判断文件是否被上传
        //    if(file.Length <= 0)
        //    {
        //        return Ok(new { msg = "文件未上传", result = -1 });
        //    }

        //    //0. 拼接文件的路径（包含文件名）
        //    string fileName = file.FileName;
        //    string filepath = environment.WebRootPath + @"\upload\" + fileName;

        //    //1. 创建一个新文件(using 语句块可以这么用了，C#8.0新特性)
        //    using FileStream fs = new FileStream(filepath, FileMode.Create);

        //    //2. 往这个新文件里写入数据流
        //    file.CopyTo(fs);

        //    //3. 关闭文件流
        //    fs.Flush();

        //    return Ok(new { relPath= $"\\upload\\{fileName}", result=1, msg="上传成功" });
        //}


        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadImg(IFormFile file, [FromServices] IWebHostEnvironment env)
        {
            if (file.Length == 0)
            {
                return Ok(new { msg = "未上传文件" });
            }

            string fileExt = Path.GetExtension(file.FileName);     //获取文件扩展名
            string fileName = Guid.NewGuid().ToString() + fileExt; //生成全球唯一文件名
            string relPath = @"\upload\" + fileName;               //拼接相对路径
            string fullPath = env.WebRootPath + relPath;          //拼接绝对路径

            //创建一个新文件(using 语句块可以这么用了，C#8.0新特性)
            using FileStream fs = new FileStream(fullPath, FileMode.Create);
            file.CopyTo(fs);
            fs.Flush();

            return Ok(new { uploadPath = relPath, result = 1, msg = "上传图片成功" });  //返回上传后的 相对路径
        }

        [HttpGet]
        public IActionResult TestNew()
        {
            //字典初始化
            Dictionary<int, string> messages = new Dictionary<int, string>
            {
                 { 404, "Page not Found"},
                 { 302, "Page moved, but left a forwarding address."},
                 { 500, "The web server can't come out to play today."}
            };

            _cache.SetString("testKey", "1212");
            TestMethod(out int i);

            return Ok(i);
        }

        /// <summary>
        /// out型参数
        /// </summary>
        /// <param name="i"></param>
        private void TestMethod(out int i)
        {
            i = GetResults().code;
        }

        /// <summary>
        /// 返回元组
        /// </summary>
        /// <returns></returns>
        private (string status, int code, string exception) GetResults()
        {
            return ("success", 1, "error");
        }


    }
}
